<!-- 合同列表 -->
<!-- 合同列表 -->
<!-- 合同列表 -->
<template>
  <div>
    <myDivider name="服务电话管理"></myDivider>

    <!-- 顶部搜索 -->
    <div class="top">
      <el-input style="width: 250px;" v-model="keytitle" placeholder="输入名称查询"></el-input>
      <el-button type="primary" @click="SouSuo">搜索</el-button>
      <el-button class="add" icon="el-icon-plus" type="success" @click="Addclick">新增</el-button>
    </div>

    <!-- 表格列表 -->
    <div class="tableBox">
      <el-table :data="tableData" style="width: 100%">
        <el-table-column align="center" prop="name" label="名称">
        </el-table-column>
        <el-table-column align="center" prop="phoneNumber" label="电话">
        </el-table-column>
        <el-table-column align="center" label="操作" width="200">
          <template slot-scope="scope">
            <el-button size="small" icon="el-icon-edit" @click="Preview('update', scope.row)"
              type="primary">修改</el-button>
            <el-button size="small" icon="el-icon-delete-solid" @click="Preview('delete', scope.row)"
              type="info">删除</el-button>
          </template>
        </el-table-column>

      </el-table>
    </div>

    <!-- 分页器 -->
    <myPagination :pageSize="pageSize" :total="total" @PageChange="PageChange" @pageSizeChange="pageSizeChange">
    </myPagination>
    <!-- 所有弹窗 -->
    <el-dialog :close-on-click-modal="false" ref="dialogVisible" :title="type == 'add' ? '新增服务电话' : '修改服务电话'"
      :visible.sync="dialogVisible" width="500px" :before-close="popCloseChange('dialogVisible')">
      <el-form :rules="rules" ref="form" :model="formData" label-width="120px">
        <el-form-item label="电话类型：" prop="category">
          <el-select style="width: 250px;" @change="SelectChange" v-model="formData.category" placeholder="请选择电话类型">
            <el-option label="手机号" value="手机号"></el-option>
            <el-option label="座机" value="座机"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="名称：" prop="name">
          <el-input style="width: 250px;" maxlength="15" v-model="formData.name" placeholder="请输入电话名称"></el-input>
        </el-form-item>
        <el-form-item label="电话号：" prop="phoneNumber">
          <el-input ref="SJH" style="width: 250px;" maxlength="20"  v-model="formData.phoneNumber" placeholder="请输入号码"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="popClose('dialogVisible')">取 消</el-button>
        <el-button type="primary" @click="popOk('dialogVisible')">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>

export default {
  data() {
    var validatePass = (rule, value, callback) => { //手机号
      if (this.formData.category == undefined) {
        callback(new Error('请先选择电话类型'));
      } else {
        let myrule
        switch (this.formData.category) {
          case '手机号':
            myrule = /^1[3|4|5|7|8][0-9]\d{8}$/
            if (myrule.test(value)) {
              callback();
            } else {
              callback(new Error('请输入正确的手机号'));
            }
            break
          case '座机':
            myrule = /0\d{2,3}-\d{7,8}|\(?0\d{2,3}[)-]?\d{7,8}|\(?0\d{2,3}[)-]*\d{7,8}/
            if (myrule.test(value)) {
              callback();
            } else {
              callback(new Error('请输入正确的座机号'));
            }
            break
        }
      }
    };
    return {
      keytitle: '',
      // 表格数据
      tableData: [],
      // 分页器
      total: 1,
      pageNum: 1,
      pageSize: 10,
      formData: {},
      rules: {
        category: [
          { required: true, message: '请选择电话类型', trigger: 'change' },
        ],
        name: [
          { required: true, message: '请输入电话名称', trigger: 'blur' },
        ],
        phoneNumber: [
          { required: true, message: '请输入号码', trigger: 'blur' },
          { validator: validatePass, trigger: 'blur' }
        ],
      },
      dialogVisible: false,
      type: '',
      companyId: null,
      updateEl: {}
    }
  },
  async activated() {
    this.keytitle = ''
    let res = await this.$api.phone.getCompanyIdByLogin()
    this.companyId = res.data
    this.getTableList()
  },
  deactivated() {

  },
  methods: {
    SelectChange() {
      this.$set(this.formData, 'phoneNumber', '')
    },
    Addclick() {
      this.type = 'add'
      this.dialogVisible = true
      this.$set(this.formData, 'category', '')
      this.$set(this.formData, 'name', '')
      this.$set(this.formData, 'phoneNumber', '')
      this.$nextTick(() => { //清除验证
        this.$refs['form'].clearValidate()
      })
    },
    async Preview(formName, row) { //表格按钮
      switch (formName) {
        case 'update':
          this.type = 'update'
          let res = await this.$api.phone.getPhoneDetail(row.id)
          console.log(res, '电话详情');
          this.updateEl = JSON.parse(JSON.stringify(res.data)) //深拷贝
          this.formData = res.data
          this.dialogVisible = true
          this.$nextTick(() => { //清除验证
            this.$refs['form'].clearValidate()
          })
          break
        case 'delete':
          this.$confirm('此操作将删除该服务电话, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(async () => {
            let res = await this.$api.phone.deletePhone(row.id)
            if (res.code == 200) {
              this.$message({
                type: 'success',
                message: '删除成功!'
              });
              this.getTableList()
            } else {
              this.$message.error(res.message);
            }

          }).catch(() => {
          });
          break
      }
    },
    popOk(formName) { //弹窗确认接口
      switch (formName) {
        case 'dialogVisible':

          this.$refs['form'].validate(async (valid) => {
            if (valid) {
              if (this.type == 'add') {
                console.log(this.formData, '新增的数据');
                let res = await this.$api.phone.insertPhone(this.formData)
                if (res.code == 200) {
                  this.$message({
                    message: '新增成功',
                    type: 'success'
                  });
                  this.getTableList()
                  this.dialogVisible = false
                } else {
                  this.$message.error(res.message);
                }
              } else {
                let {
                  id, companyId, isDelete, createTime
                } = this.updateEl
                let {
                  category, name, phoneNumber
                } = this.formData
                let res = await this.$api.phone.updatePhone({
                  id, companyId, isDelete, createTime, category, name, phoneNumber
                })
                if (res.code == 200) {
                  this.$message({
                    message: '修改成功',
                    type: 'success'
                  });
                  this.getTableList()
                  this.dialogVisible = false
                } else {
                  this.$message.error(res.message);
                }
              }
            } else {
              console.log('error submit!!');
              return false;
            }
          })
          break
      }
    },
    popClose(formName) { //弹窗取消按钮
      switch (formName) {
        case 'dialogVisible':
          this.dialogVisible = false
          break
      }
    },
    popCloseChange(formname) { // 弹窗每次关闭时的函数
      switch (formname) {
        case 'dialogVisible':

          break
      }
    },

    SouSuo() {
      // 如果点搜索的时候，当前页数在2的话，就会传2，数据少的时候获取第二页数据则会没有，所以需要手动改为1
      this.pageNum = 1
      this.getTableList()
    },
    pageSizeChange(e) { //分页器——每页数量变化
      this.pageSize = e
      this.getTableList()
    },
    PageChange(e) {//分页器——页数变化
      this.pageNum = e
      this.getTableList()
    },
    async getTableList() { // 获取表格列表
      let params = {
        "name": this.keytitle, //名称
        "companyId": this.companyId, //机构id
        "pageSize": this.pageSize,
        "pageNum": this.pageNum
      }
      let res = await this.$api.phone.getPhoneList(params)
      console.log(res, '电话列表');
      this.tableData = res.data.list
      this.total = res.data.total
    },
  },
}
</script>

<style lang="less" scoped>
.top {
  width: 100%;
  padding: 20px 30px;
  box-sizing: border-box;
  position: relative;

  .htmb {
    position: absolute;
    right: 120px;
    top: 50%;
    transform: translateY(-50%);
  }

  .add {
    position: absolute;
    right: 20px;
    top: 50%;
    transform: translateY(-50%);
  }
}

.tableBox {
  margin-top: 50px;

  /deep/ .el-table {
    .has-gutter {
      .is-leaf {
      }
    }
  }

  .SeeDetail {
    cursor: pointer;
    font-weight: 600;
    margin-left: 10px;
  }

  .ellSpan {
    white-space: nowrap;
    /* 不换行 */
    overflow: hidden;
    /* 超出部分隐藏 */
    text-overflow: ellipsis;
    /* 溢出部分显示省略号 */
  }
}
</style>